import axios from 'axios';

// API基础URL - 生产环境使用相对路径，开发环境使用完整URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || (
  import.meta.env.MODE === 'production' ? '/api' : 'http://localhost:3001/api'
);
// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': import.meta.env.VITE_API_KEY || 'dev-key'
  }
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log('API Response success:', {
      url: response.config.url,
      status: response.status,
      data: response.data
    });
    return response.data;
  },
  (error) => {
    console.error('API Error Details:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message,
      data: error.response?.data
    });
    
    // 根据错误类型提供更具体的错误信息
    if (error.code === 'ECONNREFUSED') {
      throw new Error('无法连接到服务器，请检查后端服务是否正常运行');
    } else if (error.code === 'NETWORK_ERROR') {
      throw new Error('网络连接错误，请检查网络设置');
    } else if (error.response?.status === 401) {
      throw new Error('API认证失败，请检查API Key配置');
    } else if (error.response?.status === 404) {
      throw new Error('请求的接口不存在');
    } else if (error.response?.status >= 500) {
      throw new Error('服务器内部错误，请稍后重试');
    }
    
    throw error;
  }
);

// 获取热点列表
export const getHotspots = async (platform = null) => {
  const params = {};
  if (platform) {
    params.platform = platform;
  }
  
  const response = await apiClient.get('/hotspots', { params });
  
  console.log('API Response:', response);
  
  // 服务器返回的数据结构: {success: true, data: [...], total: 10}
  // 注意：axios拦截器已经返回了response.data，所以response就是{success, data}对象
  if (!response.success || !response.data || response.data.length === 0) {
    console.error('API returned empty data:', response);
    throw new Error('API返回空数据，请检查服务器连接');
  }
  
  console.log('API data count:', response.data.length);
  return response.data;
};

// 获取趋势数据
export const getTrendData = async () => {
  const response = await apiClient.get('/trends');
  return response.data;
};

// 搜索热点
export const searchHotspots = async (query, filters = {}) => {
  const params = { ...filters };
  if (query) {
    const response = await apiClient.get(`/hotspots/search/${encodeURIComponent(query)}`, { params });
    return response.data;
  } else {
    return [];
  }
};

// 获取热点详情
export const getHotspotDetail = async (id) => {
  const response = await apiClient.get(`/hotspots/${id}`);
  return response.data;
};

// 获取平台列表
export const getPlatforms = async () => {
  const response = await apiClient.get('/hotspots/platforms/list');
  return response.data;
};

// 健康检查
export const healthCheck = async () => {
  const response = await apiClient.get('/health');
  return response.status === 'healthy';
};